package ar.com.vates.io1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class Juego {

	private int numero;
	private int intentos;
	private int record;

	public Juego() {

		// Generacion del numero random
		Random rnd = new Random();
		this.numero = rnd.nextInt(101);
		this.intentos = 0;

		this.leerRecord();

	}

	public int getNumero() {
		return numero;
	}

	public void setNumero(int numero) {
		this.numero = numero;
	}

	public int getIntentos() {
		return intentos;
	}

	public void setIntentos(int intentos) {
		this.intentos = intentos;
	}

	public boolean adivinarNumero(int numero) {
		this.intentos++;
		if (this.numero == numero) {
			if (this.record == 0) {
				System.out.println("Primer record registrado");
				this.grabarRecord();
			} else if (this.intentos < this.record) {
				System.out.println("Ha superado el record de " + record
						+ " intentos");
				this.grabarRecord();
			} else
				System.out.println("No supero el record de " + record
						+ " intentos");
			return true;
		}
		return false;
	}

	private void grabarRecord() {

		File file = new File("record.txt");
		BufferedWriter bw = null;

		try {
			if (!file.exists())
				file.createNewFile();

			bw = new BufferedWriter(new FileWriter(file));

			bw.write(String.valueOf(this.intentos));

			bw.close();
		} catch (IOException e) {
			System.out.println("Error: " + e.getMessage());
		}
	}

	private void leerRecord() {

		File file = new File("record.txt");
		BufferedReader br = null;

		try {
			if (file.exists()) {

				br = new BufferedReader(new FileReader(file));

				String rec = br.readLine();

				if (rec != null)
					this.record = Integer.parseInt(rec);
				else
					this.record = 0;

				br.close();
			} else {
				this.record = 0;
			}

		} catch (IOException e) {
			System.out.println("Error: " + e.getMessage());
		} catch (NumberFormatException e) {
			System.out.println("Error: " + e.getMessage());
		}
	}

	public int getRecord() {
		return record;
	}

	public void setRecord(int record) {
		this.record = record;
	}
}